package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.webkit.JsResult
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.LogisticsProgressResponse
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentLogisticsProgressBinding
import com.gexiaobao.pigeon.ui.adapter.LogisticsProgressAdapter
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils


/**
 * @Author      : hxw
 * @Date        : 2023/7/10 15:41
 * @Describe    : 物流信息
 */
class FragmentLogisticsProgress : BaseFragment<MallViewModel, FragmentLogisticsProgressBinding>() {

    private val mAdapter: LogisticsProgressAdapter by lazy { LogisticsProgressAdapter(arrayListOf()) }
    private lateinit var tvReceiveAddress: AppCompatTextView
    private lateinit var tvReceivePhone: AppCompatTextView

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    @SuppressLint("MissingInflatedId")
    override fun initView(savedInstanceState: Bundle?) {
        /** 初始化 swipeRecyclerView */
        mDatabind.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 0f)))
        val headerView = LayoutInflater.from(context).inflate(R.layout.header_layout_logic_address, null)
        tvReceiveAddress = headerView.findViewById(R.id.tvReceiveAddress)
        tvReceivePhone = headerView.findViewById(R.id.tvReceivePhone)
        mAdapter.addHeaderView(headerView)

        /** 数字越大 透明度越小 */
        mDatabind.llBottomSheet.background.alpha = 230
    }

    override fun onResume() {
        super.onResume()
        onRefresh()
    }

    private fun onRefresh() {
        val expressNo = arguments?.getString("expressNo").toString()
        val orderId = requireArguments().getInt("orderId")
        showLoading(getString(R.string.loading))
        mViewModel.queryNumDetail(expressNo)
        showLoading(getString(R.string.loading))
        mViewModel.getShopOrderList(orderId.toString())
    }


    @SuppressLint("SetTextI18n")
    override fun createObserver() {
        super.createObserver()
        /** 获取订单详情  */
        mViewModel.orderDetailResult.observe(viewLifecycleOwner) {
            dismissLoading()
            tvReceiveAddress.text = "收货地址:" + it.orderAddress
            tvReceivePhone.text = it.orderContactPhone
        }
        /** 物流信息查询 */
        mViewModel.LogisticsResult.observe(viewLifecycleOwner) {
            dismissLoading()
            setBottomDialogProgress(it)
            initWebView(it.trailUrl)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setBottomDialogProgress(it: LogisticsProgressResponse) {
        mDatabind.tvLogisticsType.text = SettingUtil.deliveryType(it.com)
        mDatabind.tvLogisticsNo.text = SettingUtil.cns(it.nu)

        mAdapter.setList(it.data)
        mAdapter.notifyDataSetChanged()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.ivBack, mDatabind.tvCopyLogicNo) {
            when (it) {
                mDatabind.ivBack -> {
                    nav().navigateUp()
                }

                mDatabind.tvCopyLogicNo -> {
                    /** 获取系统剪贴板 */
                    val clipboard = context?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager

                    /** 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据） */
                    val clipData = ClipData.newPlainText(null, mDatabind.tvLogisticsNo.text.toString().trim())
                    /** 把数据集设置（复制）到剪贴板  */
                    clipboard.setPrimaryClip(clipData)
                    RxToast.showToast("已复制")
                }
            }
        }
    }

    @SuppressLint("JavascriptInterface", "SetJavaScriptEnabled")
    private fun initWebView(trailUrl: String) {
        val webViewHeaderValue = KvUtils.decodeString(Constant.TOKEN)
        LogUtils.debugInfo(trailUrl)
        val map = mapOf("x-token" to webViewHeaderValue)
        mDatabind.wbLogistics.loadUrl(trailUrl, map)
        val webSettings = mDatabind.wbLogistics.settings
        webSettings.userAgentString = webSettings.userAgentString + "Android-Pigeon"
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE//不使用缓存，只从网络获取数据.
        //支持屏幕缩放
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true
        //扩大比例的缩放
        webSettings.useWideViewPort = true
        // 自适应屏幕
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.loadWithOverviewMode = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true//设置js可以直接打开窗口，如window.open()，默认为false
        webSettings.javaScriptEnabled = true//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        webSettings.setSupportZoom(true)//是否可以缩放，默认true
        webSettings.builtInZoomControls = false//是否显示缩放按钮，默认false
        webSettings.useWideViewPort = true//设置此属性，可任意比例缩放。大视图模式
        webSettings.loadWithOverviewMode = true//和setUseWideViewPort(true)一起解决网页自适应问题
        webSettings.domStorageEnabled = true//DOM Storage
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW//加载https和http混合模式

        mDatabind.wbLogistics.addJavascriptInterface(this, "android");//添加js监听 这样html就能调用客户端
        mDatabind.wbLogistics.webChromeClient = webChromeClient
        mDatabind.wbLogistics.webViewClient = webViewClient
    }

    private val webViewClient: WebViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView, url: String) {//页面加载完成
        }

        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            return super.shouldOverrideUrlLoading(view, url)
        }
    }

    private val webChromeClient: WebChromeClient = object : WebChromeClient() {

        override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
            return super.onJsAlert(view, url, message, result)
        }

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
        }

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            if (mDatabind.progressBar != null) {
                mDatabind.progressBar.visibility = View.VISIBLE
                mDatabind.progressBar.progress = newProgress
                if (newProgress == 100) {
                    mDatabind.progressBar.visibility = View.GONE
                }
            }
        }
    }

    override fun onDestroyView() {
        mDatabind.wbLogistics.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
        mDatabind.wbLogistics.clearHistory()
        mDatabind.wbLogistics.destroy()
        super.onDestroyView()
    }
}